package com.jhws.sys.cms.controller;

import com.jhws.business.aliyun.service.OSSClientService;
import com.jhws.business.customer.bo.CustomContentInfo;
import com.jhws.common.base.bo.JsonRespData;
import com.jhws.util.GetId;
import com.jhws.common.base.bo.Global;
import com.jhws.core.exception.BizException;
import com.jhws.sys.cms.service.CmsRedisService;
import com.jhws.sys.cms.bo.NodePrivateInfo;
import com.jhws.sys.cms.bo.ResourceType;
import com.jhws.sys.cms.service.AppResourceService;
import com.jhws.sys.cms.service.NodePrivateInfoService;
import com.jhws.sys.cms.service.ResourceService;
import com.jhws.sys.user.bo.TblUserDimBo;
import com.jhws.sys.user.service.ITblUserDimService;
import com.jhws.util.ObjectUtils;
import com.jhws.util.StringUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.*;

@SuppressWarnings("Duplicates")
@Controller
@RequestMapping("/cms/appResource")
public class AppResourceCtrl {
    @Resource
    private ResourceService resourceService;
    @Resource
    private AppResourceService appResourceService;
    @Resource
    private NodePrivateInfoService nodePrivateInfoService;
    @Resource
    protected ITblUserDimService IUserService;
    @Resource
    private CmsRedisService redisService;
    @Resource
    private OSSClientService ossClientService;

    /**
     * 通过条件查询资源分类
     *
     * @return
     */
    @RequestMapping("queryResourceType.x")
    @ResponseBody
    public JsonRespData queryResourceType(@RequestParam Map param) {
        String parentCode = MapUtils.getString(param, "parentCode");
        String typeCode = MapUtils.getString(param, "typeCode");
        if (parentCode != null && typeCode != null) {
            List<ResourceType> resourceTypes = resourceService.queryTypesByWhere("where parent_code = '" + parentCode + "' and type_code = '" + typeCode + "'");
            if (resourceTypes != null && resourceTypes.size() > 0) {
                return new JsonRespData("", 1, resourceTypes.get(0));
            }
        }
        return new JsonRespData("", -1, "没有这样的资源类型！");
    }

    /**
     * 查询主页树形节点
     *
     * @return
     */
    @RequestMapping("queryNodeTree.x")
    @ResponseBody
    public JsonRespData queryNodeTree() {
        return new JsonRespData("", 1, resourceService.queryTypesTree(null));
    }


    /**
     * 节点详细信息
     *
     * @return
     */
    @SuppressWarnings("unchecked")
    @RequestMapping("queryNodeInfo.x")
    @ResponseBody
    public Object queryNodeInfo(@RequestParam Map param) throws Exception {
        String typeCode = MapUtils.getString(param, "typeCode");
        if (typeCode != null) {
            List<ResourceType> resourceTypes = resourceService.queryTypesByWhere("where type_code = '" + typeCode + "'");
            if (resourceTypes != null && resourceTypes.size() == 1) {
                ResourceType resourceType = resourceTypes.get(0);
                Map retData = new HashMap();
                if (StringUtils.isNotEmpty(resourceType.getCustomContentId())) {
                    param.clear();
                    param.put("isPage", false);
                    param.put("isAnalysisCustomContent", true);
                    param.put("customTypeId", resourceType.getCustomContentId());
                    Map<String, Object> resourcesCustomType = appResourceService.queryResourceCustomType(param);
                    List customTypeList = (List) resourcesCustomType.get("list");
                    retData.put("customTypeList", customTypeList);
                }

                if (StringUtils.isNotEmpty(resourceType.getCustomPropertyPrivateId())) {
                    param.clear();
                    param.put("isPage", false);
                    param.put("isAnalysisCustomContent", true);
                    param.put("customTypeId", resourceType.getCustomPropertyPrivateId());
                    Map<String, Object> resourcesCustomType = appResourceService.queryResourceCustomType(param);
                    List customPropertyList = (List) resourcesCustomType.get("list");
                    retData.put("customPropertyList", customPropertyList);
                }

                param.clear();
                param.put("typeCode", typeCode);
                NodePrivateInfo nodePrivateInfo = nodePrivateInfoService.queryNodePrivateInfo(param);
                if (nodePrivateInfo != null) {
                    retData.put("nodePrivateInfo", nodePrivateInfo);
                }
                retData.put("ret_code", 1);
                retData.put("resourceType", resourceType);
                return retData;
            }
        }
        return new JsonRespData("", -1, "没有这样的资源类型！");
    }

    @RequestMapping("queryChildNodeInfo.x")
    @ResponseBody
    public JsonRespData queryChildNodeInfo(@RequestParam Map param) throws Exception {
        String typeCode = MapUtils.getString(param, "typeCode");
        if (typeCode != null) {
            List<ResourceType> resourceTypes = resourceService.queryTypesByWhere("where parent_code = '" + typeCode + "'");
            if (resourceTypes != null) {
                List<Map> retList = new ArrayList<>();
                Map retData;
                for (ResourceType resourceType : resourceTypes) {
                    retData = new HashMap();
                    if (StringUtils.isNotEmpty(resourceType.getCustomContentId())) {
                        param.clear();
                        param.put("isPage", false);
                        param.put("isAnalysisCustomContent", true);
                        param.put("customTypeId", resourceType.getCustomContentId());
                        Map<String, Object> resourcesCustomType = appResourceService.queryResourceCustomType(param);
                        List customTypeList = (List) resourcesCustomType.get("list");
                        retData.put("customTypeList", customTypeList);
                    }

                    if (StringUtils.isNotEmpty(resourceType.getCustomContentId())) {
                        param.clear();
                        param.put("isPage", false);
                        param.put("isAnalysisCustomContent", true);
                        param.put("customTypeId", resourceType.getCustomContentId());
                        Map<String, Object> resourcesCustomType = appResourceService.queryResourceCustomType(param);
                        List customTypeList = (List) resourcesCustomType.get("list");
                        retData.put("customTypeList", customTypeList);
                    }

                    if (StringUtils.isNotEmpty(resourceType.getCustomPropertyPrivateId())) {
                        param.clear();
                        param.put("isPage", false);
                        param.put("isAnalysisCustomContent", true);
                        param.put("customTypeId", resourceType.getCustomPropertyPrivateId());
                        Map<String, Object> resourcesCustomType = appResourceService.queryResourceCustomType(param);
                        List customPropertyList = (List) resourcesCustomType.get("list");
                        retData.put("customPropertyList", customPropertyList);
                    }

                    param.clear();
                    param.put("typeCode", resourceType.getType_code());
                    NodePrivateInfo nodePrivateInfo = nodePrivateInfoService.queryNodePrivateInfo(param);
                    if (nodePrivateInfo != null) {
                        retData.put("nodePrivateInfo", nodePrivateInfo);
                    }

                    retData.put("resourceType", resourceType);
                    retList.add(retData);
                }
                return new JsonRespData("", 1, retList);
            }
        }
        return new JsonRespData("", -1, "没有这样的资源类型！");
    }

    /**
     * 保存资源
     *
     * @param r               资源
     * @param customDescribes 自定义描述
     * @param customKeys      自定义key
     * @param customValues    自定义value
     * @return
     * @throws IOException
     */
    @RequestMapping("saveResource.x")
    @ResponseBody
    public JsonRespData saveResource(com.jhws.sys.cms.bo.Resource r,
                                     String[] customDescribes,
                                     String[] customKeys,
                                     String[] customValues) throws IOException, InvocationTargetException, IllegalAccessException {
        TblUserDimBo userBo = IUserService.currentUser();
        //如果有自定义类容转为json
        List<CustomContentInfo> customContentInfos = new ArrayList<>();
        CustomContentInfo contentInfo;
        if (customKeys != null && customValues != null) {
            if (customValues.length != customKeys.length) {
                new JsonRespData("", -1, "自定义内容错误！");
            }
            for (int i = 0; i < customKeys.length; i++) {
                contentInfo = new CustomContentInfo();
                if (customDescribes != null && customDescribes.length > i && org.apache.commons.lang.StringUtils.isNotEmpty(customDescribes[i])) {
                    contentInfo.setCustomDescribe(customDescribes[i]);
                }
                contentInfo.setCustomKey(customKeys[i]);
                contentInfo.setCustomValue(customValues[i]);
                if (!org.apache.commons.lang.StringUtils.isEmpty(customValues[i])) {
                    customContentInfos.add(contentInfo);
                }
            }
        }

        if (customContentInfos.size() > 0) {
            String customContent = com.alibaba.fastjson.JSON.toJSONString(customContentInfos);
            r.setCustomContent(customContent);
        }
        //将临时文件拷贝
        if (StringUtils.isNotEmpty(r.getIcon_url())) {
            String suffix = FilenameUtils.getExtension(r.getIcon_url());
            String imagePath = "cms/file/" + GetId.randomID() + "." + suffix;
            ossClientService.gerneralCopyFile(r.getIcon_url(), imagePath);
            r.setIcon_url(imagePath);
        }
        r.setIsApproved(Global.CMS_IS_APPROVED);
        r.setApprovedState("正在审核");
        r.setCreator(userBo.getLogName());
        //保存资源
        appResourceService.saveResource(r);
        //清空一下redis
        redisService.emptyRedisCMS();
        return new JsonRespData("", 1, "");
    }

    /**
     * 查询资源
     *
     * @param param
     * @return
     * @throws IOException
     */
    @RequestMapping("queryResourceList.x")
    @ResponseBody
    public JsonRespData queryResourceList(@RequestParam Map param) throws IOException {
        Map<String, Object> resources = appResourceService.queryResourcePage(param);
        return new JsonRespData("", 1, resources);
    }

    /**
     * 查询所有资源
     *
     * @param param
     * @return
     * @throws IOException
     */
    @SuppressWarnings("unchecked")
    @RequestMapping("queryAllResourceList.x")
    @ResponseBody
    public JsonRespData queryAllResourceList(@RequestParam Map param) throws IOException {
        if (!SecurityUtils.getSubject().hasRole(Global.ROLE_SUPPER_ADMIN)) {
            throw new BizException("没有权限查询所有资源！");
        }
        param.put("isAllUserResource", true);
        Map<String, Object> resources = appResourceService.queryResourcePage(param);
        return new JsonRespData("", 1, resources);
    }

    /**
     * 查询已分配资源
     *
     * @param param
     * @return
     * @throws IOException
     */
    @RequestMapping("queryAlreadyResourceList.x")
    @ResponseBody
    public Object queryAlreadyResourceList(@RequestParam Map param) throws IOException {
        return appResourceService.queryAlreadyResource(param);
    }

    /**
     * 功能：将资源分配给相应的小区
     *
     * @param resourceCodes 资源ID
     * @param commGroupId   小区分组Id
     * @return 成功或者失败
     * @throws Exception
     */
    @RequestMapping("submitAssignsResource.x")
    @ResponseBody
    public JsonRespData submitAssignsResource(String typeCode, String resourceCodes, String commGroupId, String commCode) throws Exception {
        String[] resourceIDs = null;
        if (StringUtils.isNotEmpty(resourceCodes)) {
            resourceIDs = resourceCodes.split(",");
        }
        //分配资源
        appResourceService.updateResource(typeCode, resourceIDs, commGroupId, commCode);
        //清空一下redis
        redisService.emptyRedisCMS();
        return new JsonRespData("", 1, "");
    }

    /**
     * 功能：将资源分配给相应的小区
     *
     * @param resourceCode 资源ID
     * @param commGroupId  小区分组Id
     * @return 成功或者失败
     * @throws Exception
     */
    @RequestMapping("assignsResource.x")
    @ResponseBody
    public JsonRespData assignsResource(String typeCode, String resourceCode, String commGroupId, String commCode, boolean isAssigns) throws Exception {
        //分配资源
        appResourceService.updateResource(typeCode, resourceCode, commGroupId, commCode, isAssigns);
        //清空一下redis
        redisService.emptyRedisCMS();
        return new JsonRespData("", 1, "");
    }

    /**
     * 审核状态
     *
     * @param resource_id   资源Id
     * @param isApproved    是否通过
     * @param approvedState 状态原因
     * @return
     * @throws Exception
     */
    @RequestMapping("approvedState.x")
    @ResponseBody
    public JsonRespData approvedState(String resource_id, String isApproved, String approvedState) throws Exception {
        String set = " set isApproved='" + isApproved + "'";
        String where = " where resource_id = '" + resource_id + "' or parentResourceId='" + resource_id + "'";
        if (Global.CMS_NOT_APPROVED.equals(isApproved)) {
            set += " ,approvedState = '" + "未通过审核\n原因：" + approvedState + "' ";
            appResourceService.deleteResource(" where parentResourceId='" + resource_id + "'");
        } else if (Global.CMS_APPROVED.equals(isApproved)) {
            set += " ,approvedState = '审核通过' ";
        }
        appResourceService.updateResource(set, where);
        //清空一下redis
        redisService.emptyRedisCMSAll();
        return new JsonRespData("", 1, "");
    }

    /**
     * 删除资源
     *
     * @param r
     * @param isNotDeleteOss
     * @return
     */
    @RequestMapping("deleteResource.x")
    @ResponseBody
    public JsonRespData deleteResource(com.jhws.sys.cms.bo.Resource r, boolean isNotDeleteOss) {
        com.jhws.sys.cms.bo.Resource resource = appResourceService.queryResourceIdByResource(r.getResource_id());
        //如果oss上的资源被删除，就删除所以相关的资源条目
        if (!isNotDeleteOss && resource.getIcon_url() != null && !ObjectUtils.isHttpAddress(resource.getIcon_url())) {
            //先删除oss上的文件
            appResourceService.deleteRemoteFile(r, resource.getIcon_url());
        } else {
            appResourceService.deleteResource("where resource_id='" + r.getResource_id() + "' or parentResourceId='" + r.getResource_id() + "'");
        }
        //清空一下redis
        redisService.emptyRedisCMS();
        return new JsonRespData("", 1, "");
    }

    /**
     * 上传文件
     *
     * @param file    文件头
     * @param request
     * @param isTemp  是否放入临时文件
     * @return
     * @throws IOException
     */
    @RequestMapping("uploadFile.x")
    @ResponseBody
    public JsonRespData uploadFile(@RequestParam("file") MultipartFile file, HttpServletRequest request, boolean isTemp) throws IOException {
        //上传文件到远程图片服务器
        String suffix = FilenameUtils.getExtension(file.getOriginalFilename());
        String path;
        if (isTemp) {
            path = "temp_1day/" + GetId.randomID() + "." + suffix;
        } else {
            path = "cms/file/" + GetId.randomID() + "." + suffix;
        }
        ossClientService.updateFile(path, file.getInputStream());

        String url = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
                + request.getContextPath();
        url += "/cms/resource/downloadRemoteFile.x?path=" + path;
        Map<String, String> ret = new HashMap<>();
        ret.put("imagePath", path);
        ret.put("imageUrl", url);
        return new JsonRespData("", 1, ret);
    }
}
